package com.han.hotelplat.service.employee.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.stat.JdbcConnectionStat.EntryMBean;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.han.hotelplat.cache.redis.IRedisCache;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.base.EntityManage;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.AreaHelp;
import com.han.hotelplat.comm.utils.MD5;
import com.han.hotelplat.comm.utils.MsgHelp;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.comm.utils.UUIDUtils;
import com.han.hotelplat.controller.employee.EmployeeController;
import com.han.hotelplat.dao.employee.EmployeeDao;
import com.han.hotelplat.dao.emtask.EmtaskDao;
import com.han.hotelplat.dao.wallet.WalletDao;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.emtask.Emtask;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.pojo.task.Task;
import com.han.hotelplat.pojo.wallet.Wallet;
import com.han.hotelplat.service.childtask.ChildTaskService;
import com.han.hotelplat.service.employee.EmployeeService;
import com.han.hotelplat.service.emtask.EmTaskService;
import com.han.hotelplat.service.hotel.HotelService;
import com.han.hotelplat.service.task.TaskService;

@Service
public class EmployeeServiceImpl implements EmployeeService{
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private IRedisCache redisCache;
	@Autowired
	private WalletDao walletDao;
	@Autowired
	private  EntityManage entityManage;
	@Autowired
	private EmTaskService emTaskService;
	@Autowired
	private ChildTaskService childTaskService;
	@Autowired
	private TaskService taskService;
	
	@Override
	public Map<String, Object> login(String phone, String code) {
		Map<String, Object>returndata = new HashMap<String, Object>();
		boolean auth = true;
		for(String whitePhone : Constant.whiteList){
			if(whitePhone.equals(phone)){
				auth=false;
			}
		}
		Employee employee = employeeDao.findByPhone(phone);
		String cachedvcode = redisCache.get(Constant.CACHE_PHONE_VCODE_LOGIN_EM+phone);
		if(auth && !code.equals(cachedvcode)){
			returndata.put("code", -1);
			returndata.put("message", "验证码错误");
			return returndata;
		}
		if(employee == null){//用户不存在则需要创建新用户
			employee = new Employee();
			employee.setTel(phone);
			employee.setCreattime(new Date());
			employee.setRealname("");
			employee.setUsername(phone);
			employee.setUserid(UUIDUtils.getUUID()+"");
			employee.setState(Constant.USER_STATE_CREAT);
			//employee.setSex(Constant.SEX[1]);
			employee.setLevel(4);//默认清洁等级4
			employeeDao.save(employee);
			//创帮工钱包
			Wallet wallet = new Wallet();
			wallet.setUserid(employee.getUserid());
			wallet.setUsertype(Constant.WALLET_USER_TYPE_EM);
			wallet.setState(Constant.WALLET_STATE_NOTACTIVE);
			wallet.setBalance(0f);
			wallet.setOverdraft(0f);
			walletDao.save(wallet);
		}
		employee.setLastlogintime(new Date());
		employeeDao.update(employee);
		if(StringUtils.isNotBlank(employee.getBankcard())){
			employee.setBankcardno(JSONObject.parseObject(employee.getBankcard()).getString("bankcardno"));
			employee.setBankcode(JSONObject.parseObject(employee.getBankcard()).getString("bankcode"));
			employee.setBankcardtype(JSONObject.parseObject(employee.getBankcard()).getString("bankcardtype"));
		}
		returndata.put("code", 0);
		returndata.put("message", "登陆成功");
		returndata.put("user", employee);
		
		redisCache.delete(Constant.CACHE_PHONE_VCODE_LOGIN_EM+phone);
		
		return returndata;
	}

	@Override
	public Map quickLogin(String userid) {
		Employee employee = employeeDao.findEmployeeByUerid(userid);
		Map<String, Object>returndata = new HashMap<String, Object>();
		if(employee == null){
			returndata.put("code", -1);
			returndata.put("message", "口令已失效");
			return returndata;
		}
		employee.setLastlogintime(new Date());
		employeeDao.update(employee);
		if(StringUtils.isNotBlank(employee.getBankcard())){
			employee.setBankcardno(JSONObject.parseObject(employee.getBankcard()).getString("bankcardno"));
			employee.setBankcode(JSONObject.parseObject(employee.getBankcard()).getString("bankcode"));
			employee.setBankcardtype(JSONObject.parseObject(employee.getBankcard()).getString("bankcardtype"));
		}
		returndata.put("code", 0);
		returndata.put("message", "登陆成功");
		returndata.put("user", employee);
		return returndata;
	}
	
	@Override
	public void update(Employee employee) {
		employeeDao.update(employee);
	}

	@Override
	public Map<String, Object> searchEmployee(String taskid, Integer areaCode,
			String condition, Integer pageNum, Short pageSize) {
		List<Employee> eli = new ArrayList<Employee>();
		Map<String, Object> resMap = new HashMap<String, Object>();
		Pager<Employee> data = new Pager<Employee>();
		String hql = " from Employee where 1=1 ";
		if(condition!=null && !condition.isEmpty()){
			hql = hql + " and realname like '%"+condition+"%' or tel like '%"+condition+"%'";
		}else{
			if(areaCode != null && areaCode.intValue()>100000){
				String w_areaCode = areaCode.toString();
				if(areaCode != null && areaCode.intValue()>100000){//区域码至少6位
					int x=0;
					String w_area="";
					if(w_areaCode.endsWith("0000")) {
						//精度 省份
						x=9999;
					}else if(w_areaCode.endsWith("00")) {
						//精度 市
						x=99;
					}else {
						//精度 区
						x=0;
					}
					//要的   - 条件  >=0
					//410610-410000 <= 9999
					//410610-410600 <= 99
					//410610-410610 == 0
					w_area=" and convert(area,signed) - "+areaCode +" >=0 ";
					w_area+=" and convert(area,signed) - "+areaCode +" <= "+x;
					hql = hql + w_area;
				}
			}
		}
		
		data = entityManage.findByHqlForPage(hql, pageNum, pageSize);
		Task t= taskService.getHotelTaskDteail(taskid);
		
		for(Employee e : data.getList()){
			if(!StrUtil.isNullOrEmpty(e.getArea())){
				e.setAreaModel(AreaHelp.getInstance().getAreaModels(e.getArea()));
			}
			if(StringUtils.isNotBlank(e.getBankcard())){
				e.setBankcardno(JSONObject.parseObject(e.getBankcard()).getString("bankcardno"));
				e.setBankcode(JSONObject.parseObject(e.getBankcard()).getString("bankcode"));
				e.setBankcardtype(JSONObject.parseObject(e.getBankcard()).getString("bankcardtype"));
			}
			//查询服务的历史纪录
			List<Emtask> li = emTaskService.getEmTaskByHotelid(e.getUserid(),t.getHotelid());
			e.setServercount(li.size());
			
			int res = emTaskService.isAcceptTask(e.getUserid(), taskid);
			if(res >= 0){
				if(res == 7){//报名后取消的再次添加
					e.setState(0);
					eli.add(e);
				}else{
					e.setState(res);
					eli.add(e);
				}
			}else{
				resMap.put("code", -1);
				resMap.put("message", "订单异常不能招募帮工");
				return resMap;
			}
		}
		data.setList(eli);
		resMap.put("code", 0);
		resMap.put("eli", data);
		resMap.put("message", "数据获取成功");
		return resMap;
	}

	@Override
	public Employee getEmployee(String userid) {
		Employee employee = employeeDao.findEmployeeByUerid(userid);
		if(employee != null && StringUtils.isNotBlank(employee.getBankcard())){
			employee.setBankcardno(JSONObject.parseObject(employee.getBankcard()).getString("bankcardno"));
			employee.setBankcode(JSONObject.parseObject(employee.getBankcard()).getString("bankcode"));
			employee.setBankcardtype(JSONObject.parseObject(employee.getBankcard()).getString("bankcardtype"));
		}
		return employee;
	}

	@Override
	public void save(Employee em) {
		employeeDao.save(em);
	}

	@Override
	public Pager<Employee> findEmployee(String startDate, String endDate, Integer state,
			Integer level, Integer areaCode, String condition, Integer pageNo, String hotelName, Integer sortType) {
		Pager<Employee> data = new Pager<Employee>(20, 0, 0, 0, new ArrayList<Employee>());
		StringBuffer hql = new StringBuffer("select new Employee (em.id, em.userid,em.realname,em.sex,"
				+ "em.workyears,em.area,em.state,em.tel,w.balance, em.idcard,em.bankcard, em.creattime) from Employee as em, Wallet w where w.userid=em.userid ");
		if(condition!=null && !condition.isEmpty()){
			hql.append(" and (realname like '%"+condition+"%'"
					+ " or tel like '%"+condition+"%'"
					+ " or introduceriname like '%"+condition+"%'"
					+ " or emergencytel like '%"+condition+"%')");
		}
		if(level != null){
			hql.append(" and em.level="+level);
		}
		if(state != null){
			if( state.intValue() == -1){//查询资料不全的
				hql.append("and em.state=1 and (em.realname is null or em.sex is null "
						+ " or em.workyears is null or em.level is null or em.idcard is null "
						+ " or em.facepic is null or em.backpic is null or em.area is null "
						+ " or em.address is null)");
			}else if(state.intValue() == 1){//未审核的不能包括那些资料不全的
				hql.append(" and em.state=1 and em.realname is not null and em.sex is not null "
						+ " and em.workyears is not null and em.level is not null and em.idcard is not null "
						+ " and em.facepic is not null and em.backpic is not null and em.area is not null "
						+ " and em.address is not null ");
			}else{
				hql.append(" and em.state="+state);
			}
		}
		if(areaCode != null && areaCode.intValue()>100000){
			String w_areaCode = areaCode.toString();
			int x=0;
			String w_area="";
			if(w_areaCode.endsWith("0000")) {
				//精度 省份
				x=9999;
			}else if(w_areaCode.endsWith("00")) {
				//精度 市
				x=99;
			}else {
				//精度 区
				x=0;
			}
			//要的   - 条件  >=0
			//410610-410000 <= 9999
			//410610-410600 <= 99
			//410610-410610 == 0
			w_area=" and convert(area,signed) - "+areaCode +" >=0 ";
			w_area+=" and convert(area,signed) - "+areaCode +" <= "+x;
			hql.append(w_area);
		}
		if(startDate != null && !startDate.isEmpty()){
			hql.append(" and em.creattime>='"+startDate+" 00:00:00'");
		}			  
		if(endDate != null && !endDate.isEmpty()){
			hql.append(" and em.creattime<='"+endDate+" 23:59:59'");
		}
		
		if(StringUtils.isNotBlank(hotelName)){
			String sql = "SELECT et.emid FROM tb_hotel AS h, tb_em_task AS et "
					+ "WHERE et.hotelid=h.id AND h.hotelname like '%"+hotelName+"%' GROUP BY et.emid";
			List<String> li = entityManage.findBySql(sql);
			StringBuffer sb = new StringBuffer(" and em.userid in(");
			if(li.size() == 0){
				return data;
			}
			for(int i=0; i<li.size(); i++){
				String emid = li.get(i);
				if(i == (li.size()-1)){
					sb.append("'"+emid +"')");
				}else{
					sb.append("'"+emid+"',");
				}
			}
			
			hql.append(sb.toString());
		}
		if(sortType == null){
			hql.append(" order by em.creattime desc");
		}else if(sortType.intValue() == 1){//按照创建时间降序
			hql.append(" order by w.balance desc");
		}else if(sortType.intValue() == 2){//按照创建时间升序
			hql.append(" order by w.balance asc");
		}else if(sortType.intValue() == 3){//按照钱包余额降序
			hql.append(" order by w.balance desc");
		}else if(sortType.intValue() == 4){//按照钱包余额升序
			hql.append(" order by w.balance asc");
		}
		
		data = entityManage.findByHqlForPage(hql.toString(), pageNo, (short)20);
		for (Employee em : data.getList()) {
			float roomcount = childTaskService.getEmRoom(em.getUserid());
			em.setRoomcount(roomcount);
			if(em != null && StringUtils.isNotBlank(em.getBankcard())){
				em.setBankcardno(JSONObject.parseObject(em.getBankcard()).getString("bankcardno"));
				em.setBankcode(JSONObject.parseObject(em.getBankcard()).getString("bankcode"));
				em.setBankcardtype(JSONObject.parseObject(em.getBankcard()).getString("bankcardtype"));
			}
			if(!StrUtil.isNullOrEmpty(em.getArea())){
				em.setAreaModel(AreaHelp.getInstance().getAreaModels(em.getArea()));
			}
		}
		return data;
	}

	@Override
	public Employee findEmployeeByTel(String tel) {
		List<Employee> emli = employeeDao.findByProperty("tel", tel);
		Employee em = emli.size()>0?emli.get(0):null;
		if(em != null && StringUtils.isNotBlank(em.getBankcard())){
			em.setBankcardno(JSONObject.parseObject(em.getBankcard()).getString("bankcardno"));
			em.setBankcode(JSONObject.parseObject(em.getBankcard()).getString("bankcode"));
			em.setBankcardtype(JSONObject.parseObject(em.getBankcard()).getString("bankcardtype"));
		}
		return em;
	}

	@Override
	public Map<String, Integer> getEmCount() {
		String todaysql = "SELECT COUNT(*) FROM tb_employee WHERE TO_DAYS(date_format(creattime,'%Y-%m-%d')) = TO_DAYS(now())";
		String weeksql = "SELECT COUNT(*) FROM tb_employee WHERE YEARWEEK(date_format(creattime,'%Y-%m-%d'),1) = YEARWEEK(now())";
		String mothsql = "SELECT  COUNT(*) FROM  tb_employee WHERE DATE_FORMAT( creattime, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' )"; 
		String allsql = "SELECT  COUNT(*) FROM  tb_employee"; 
		
		List tc = entityManage.findBySql(todaysql);
		List wc = entityManage.findBySql(weeksql);
		List mc = entityManage.findBySql(mothsql);
		List ac = entityManage.findBySql(allsql);
		int todaycount= Integer.parseInt(tc.size() == 0?"0":tc.get(0).toString());//今日
		int weekcount = Integer.parseInt(wc.size() == 0?"0":wc.get(0).toString());//本周
		int monthcount = Integer.parseInt(mc.size() == 0?"0":mc.get(0).toString());//本月
		int allcount = Integer.parseInt(ac.size() == 0?"0":ac.get(0).toString());//所有
		
		Map<String, Integer> data = new HashMap<String, Integer>();
		data.put("todaycount", todaycount);
		data.put("weekcount", weekcount);
		data.put("monthcount", monthcount);
		data.put("allcount", allcount);
		return data;
	}

	@Override
	public Map loginByPassword(String phone, String password) {
		Map<String, Object>returndata = new HashMap<String, Object>();
		Employee employee = employeeDao.findByPhone(phone);
		if(employee != null){
			if(employee.getPassword() != null){
				if(employee.getPassword().equals(MD5.toMD5(password))){
					if(employee != null && StringUtils.isNotBlank(employee.getBankcard())){
						employee.setBankcardno(JSONObject.parseObject(employee.getBankcard()).getString("bankcardno"));
						employee.setBankcode(JSONObject.parseObject(employee.getBankcard()).getString("bankcode"));
						employee.setBankcardtype(JSONObject.parseObject(employee.getBankcard()).getString("bankcardtype"));
					}
					returndata.put("code", 0);
					returndata.put("message", "登陆成功");
					returndata.put("user", employee);
					return returndata;
				}
				returndata.put("code", -1);
				returndata.put("message", "密码错误");
				returndata.put("user", employee);
				return returndata;
			}
			returndata.put("code", -1);
			returndata.put("message", "未设置登陆密码");
			returndata.put("user", employee);
			return returndata;
		}
		returndata.put("code", -1);
		returndata.put("message", "用户不存在");
		returndata.put("user", employee);
		return returndata;
	}

	@Override
	public List<Employee> expEmployee(String startDate, String endDate,
			Integer state, Integer level, Integer areaCode, String condition) {
		StringBuffer hql = new StringBuffer("select new Employee (em.id, em.userid,em.realname,em.sex,"
				+ "em.workyears,em.area,em.state,em.tel,w.balance, em.idcard, em.bankcard, em.creattime) from Employee as em, Wallet w where w.userid=em.userid ");
		if(condition!=null && !condition.isEmpty()){
			hql.append(" and (realname like '%"+condition+"%'"
					+ " or tel like '%"+condition+"%'"
					+ " or introduceriname like '%"+condition+"%'"
					+ " or emergencytel like '%"+condition+"%')");
		}
		if(level != null){
			hql.append(" and em.level="+level);
		}
		if(areaCode != null && areaCode.intValue()>100000){
			String w_areaCode = areaCode.toString();
			int x=0;
			String w_area="";
			if(w_areaCode.endsWith("0000")) {
				//精度 省份
				x=9999;
			}else if(w_areaCode.endsWith("00")) {
				//精度 市
				x=99;
			}else {
				//精度 区
				x=0;
			}
			//要的   - 条件  >=0
			//410610-410000 <= 9999
			//410610-410600 <= 99
			//410610-410610 == 0
			w_area=" and convert(area,signed) - "+areaCode +" >=0 ";
			w_area+=" and convert(area,signed) - "+areaCode +" <= "+x;
			hql.append(w_area);
		}
		if(startDate != null && !startDate.isEmpty()){
			hql.append(" and em.creattime>='"+startDate+" 00:00:00'");
		}			  
		if(endDate != null && !endDate.isEmpty()){
			hql.append(" and em.creattime<='"+endDate+" 23:59:59'");
		}	
		hql.append(" order by em.creattime desc");
		List<Employee>  list= entityManage.findByHql(hql.toString());
		for (Employee em : list) {
			Float roomcount = childTaskService.getEmRoom(em.getUserid());
			em.setRoomcount(roomcount);
			if(em != null && StringUtils.isNotBlank(em.getBankcard())){
				em.setBankcardno(JSONObject.parseObject(em.getBankcard()).getString("bankcardno"));
				em.setBankcode(JSONObject.parseObject(em.getBankcard()).getString("bankcode"));
				em.setBankcardtype(JSONObject.parseObject(em.getBankcard()).getString("bankcardtype"));
			}
			if(!StrUtil.isNullOrEmpty(em.getArea())){
				em.setAreaModel(AreaHelp.getInstance().getAreaModels(em.getArea()));
			}
		}
		return list;
	}

	@Override
	public void noticeEmAddInfo() {
		String hql = "from Employee where state = "+Constant.USER_STATE_CREAT
				+" or state = "+Constant.USER_STATE_NO_PASS;
		List<Employee> li = entityManage.findByHql(hql);
		/*try {
			MsgHelp.noticeEm("18825117885");
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		for(Employee e : li){
			try {
				if(!StrUtil.isNullOrEmpty(e.getTel())){
					MsgHelp.noticeEm(e.getTel());
				}
			} catch (ClientException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

}
